package com.thermal.thermal_inspection.controller;

import com.thermal.thermal_inspection.common.CommonResponse;
import com.thermal.thermal_inspection.entity.Map;
import com.thermal.thermal_inspection.entity.MapDetail;
import com.thermal.thermal_inspection.service.MapService;
import com.thermal.thermal_inspection.service.UnitService;
import com.thermal.thermal_inspection.vo.AddMapVO;
import com.thermal.thermal_inspection.vo.MapDetailVO;
import com.thermal.thermal_inspection.vo.MapVO;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/inspection/map")
public class MapController {
    @Autowired
    MapService mapService;
    @Autowired
    UnitService unitService;

    private static final Logger logger = Logger.getLogger(MapController.class);

    /**
     * 查询所有已保存地图（带分页功能）
     */
    @GetMapping("")
    public CommonResponse<MapVO> getMaps(@RequestParam int pageNum, @RequestParam int pageSize){
        MapVO mapVO = new MapVO();
        //去掉总地图和无
        List<Map> mapList = mapService.getMaps(pageNum, pageSize);
        if(mapList.isEmpty()) {
            pageNum--;
            mapList = mapService.getMaps(pageNum, pageSize);
        }
        int total = mapService.getTotal();
        mapVO.setMaps(mapList);
        mapVO.setTotal(total);
        if(mapList.isEmpty()){
            logger.error("无已保存地图");
            return CommonResponse.createForError("无已保存地图");
        }
        logger.info("查询地图成功");
        return CommonResponse.createForSuccess("SUCCESS", mapVO);
    }

    /**
     * 查询地图所有点位
     */
    @GetMapping("/{mapId}")
    public CommonResponse<List<MapDetailVO>> getAllMapDetail(@PathVariable int mapId){
        List<MapDetailVO> mapDetailVOList = mapService.getAllMapDetail(mapId);
        if(mapService.existMap(mapId) == null){
            logger.error("该地图不存在");
            return CommonResponse.createForError("该地图不存在");
        }
        if(mapDetailVOList.isEmpty()){
            logger.error("该地图无点位");
            return CommonResponse.createForError("该地图无点位");
        }
        logger.info("查询地图点位成功");
        return CommonResponse.createForSuccess("SUCCESS", mapDetailVOList);
    }

    /**
     * 查询特定地图点位
     */
    @GetMapping("/detail/{mapDetailId}")
    public CommonResponse<MapDetailVO> getOneMapDetail(@PathVariable int mapDetailId){
        MapDetailVO mapDetailVO = mapService.getOneMapDetail(mapDetailId);
        if(mapDetailVO == null){
            logger.error("该地图点位不存在");
            return CommonResponse.createForError("该地图点位不存在");
        }
        logger.info("查询地图点位成功");
        return CommonResponse.createForSuccess("SUCCESS", mapDetailVO);
    }

    /**
     * 新增地图
     */
    @PostMapping("")
    public CommonResponse<Map> addMap(@RequestBody AddMapVO addMapVO){
        String mapName = addMapVO.getMapName();

        //判断地图名是否存在
        if(mapService.getMapByMapName(mapName) != null){
            logger.error("地图名重复，请更换地图名");
            return CommonResponse.createForError("地图名重复，请更换地图名");
        }

        //用for循环添加地图点位
        List<AddMapVO.MapPoints> mapPointsList = addMapVO.getMapPoints();
        for(AddMapVO.MapPoints mapPoints: mapPointsList){
            String mapLongitude = mapPoints.getMapLongitude();
            String mapLatitude = mapPoints.getMapLatitude();
            int unitId = mapPoints.getUnitId();
            //判断机组是否存在
            if(!unitService.existUnit(unitId)){
                logger.error(unitId + "机组不存在，地图新增失败");
                return CommonResponse.createForError("机组不存在，地图新增失败");
            }

            String mapDetailDesc = mapPoints.getMapDetailDesc();
            String mapNfcMsg = mapPoints.getMapNfcMsg();

            int rows = mapService.addMap(mapName, mapLongitude, mapLatitude, unitId, mapDetailDesc, mapNfcMsg);
            if (rows == 0){
                logger.error("地图新增失败");
                return CommonResponse.createForError("地图新增失败");
            }
        }

        //最后返回新增的地图
        Map map = mapService.getMapByMapName(mapName);
        if (map == null){
            logger.error("地图新增失败");
            return CommonResponse.createForError("地图新增失败");
        }
        logger.info("地图新增成功");
        return CommonResponse.createForSuccess("SUCCESS", map);
    }

    /**
     * 为已有地图添加点位
     */
    @PostMapping("/mapDetail")
    public CommonResponse<Object> addMapDetail(@RequestBody MapDetail mapDetail){
        int mapId = mapDetail.getMapId();
        String mapLongitude = mapDetail.getMapLongitude();
        String mapLatitude = mapDetail.getMapLatitude();
        int unitId = mapDetail.getUnitId();
        String mapDetailDesc = mapDetail.getMapDetailDesc();
        String mapNfcMsg = mapDetail.getMapNfcMsg();

        //先判断地图是否存在
        if(mapService.existMap(mapId) == null){
            logger.error("地图不存在");
            return CommonResponse.createForError("地图不存在");
        }

        //判断机组是否存在
        if(!unitService.existUnit(unitId)){
            logger.error(unitId + "机组不存在，地图新增失败");
            return CommonResponse.createForError("机组不存在，地图新增失败");
        }

        //判断mapDetailDesc是否存在，不能重名
        if(mapService.existMapDetailDesc(mapId, mapDetailDesc)){
            logger.error("点位名重复，地图新增失败");
            return CommonResponse.createForError("点位名重复，地图新增失败");
        }

        int rows = mapService.addMapDetail(mapId, mapLongitude, mapLatitude, unitId, mapDetailDesc, mapNfcMsg);
        if(rows == 0){
            logger.error("地图添加点位失败");
            return CommonResponse.createForError("地图添加点位失败");
        }

        logger.info("地图添加点位成功");
        return CommonResponse.createForSuccess("SUCCESS", null);
    }

    /**
     * 修改地图名称
     */
    @PutMapping("")
    public CommonResponse<Object> changeMapName(@RequestBody Map map){
        int mapId = map.getMapId();
        String mapName = map.getMapName();

        //先判断地图是否存在
        if(mapService.existMap(mapId) == null){
            logger.error("地图不存在");
            return CommonResponse.createForError("地图不存在");
        }

        //判断地图名是否存在
        if(mapService.getMapByMapName(mapName) != null){
            logger.error("已存在地图名，请更换地图名");
            return CommonResponse.createForError("已存在地图名，请更换地图名");
        }

        int rows = mapService.changeMapName(mapId, mapName);
        if(rows == 0){
            logger.error("修改地图名称失败");
            return CommonResponse.createForError("修改地图名称失败");
        }
        logger.info("修改地图名称成功");
        return CommonResponse.createForSuccess("SUCCESS", null);
    }

    /**
     * 修改地图点位信息
     */
    @PutMapping("/detail")
    public CommonResponse<Object> changeMapDetail(@RequestBody MapDetail mapDetail){
        int mapDetailId = mapDetail.getMapDetailId();
        int mapId = mapDetail.getMapId();
        String mapDetailDesc = mapDetail.getMapDetailDesc();

        //先查看地图点位是否存在
        if(!mapService.existMapDetail(mapDetailId)){
            logger.error("修改地图点位失败，地图点位不存在");
            return CommonResponse.createForError("地图点位不存在");
        }

        //判断地图是否存在
        if(mapService.existMap(mapId) == null){
            logger.error("修改地图点位失败，地图不存在");
            return CommonResponse.createForError("地图不存在");
        }

        //判断修改后的名字是否重复
        if (mapService.existMapDetailDesc(mapId, mapDetailDesc)) {
            logger.error("地图点位名重复");
            return CommonResponse.createForError("地图点位名重复");
        }

        //修改信息
        int rows = mapService.changeMapDetail(mapDetailId, mapId, mapDetailDesc);
        if(rows == 0){
            logger.error("修改地图点位失败");
            return CommonResponse.createForError("修改地图点位失败");
        }
        logger.info("修改地图点位成功");
        return CommonResponse.createForSuccess("SUCCESS", null);
    }

    /**
     * 删除地图
     */
    @DeleteMapping("/{mapId}")
    public CommonResponse<Object> deleteMap(@PathVariable int mapId){
        //判断地图是否存在
        if(mapService.existMap(mapId) == null){
            logger.error("删除地图失败，地图不存在");
            return CommonResponse.createForError("删除地图失败，地图不存在");
        }

        //mapId为1不能删
        if(mapId == 1){
            logger.error("总地图不能删除");
            return CommonResponse.createForError("总地图不能删除");
        }

        //删除地图
        int rows = mapService.deleteMap(mapId);
        if(rows == 0){
            logger.error("删除地图失败");
            return CommonResponse.createForError("删除地图失败");
        }
        logger.info("删除地图成功");
        return CommonResponse.createForSuccess("SUCCESS", null);
    }

    /**
     * 删除地图点位
     */
    @DeleteMapping("/detail/{mapDetailId}")
    public CommonResponse<Object> deleteMapDetail(@PathVariable int mapDetailId){
        //先查看地图点位是否存在
        if(!mapService.existMapDetail(mapDetailId)){
            logger.error("修改地图点位失败，地图点位不存在");
            return CommonResponse.createForError("修改地图点位失败，地图点位不存在");
        }

        //删除地图点位
        int rows = mapService.deleteMapDetail(mapDetailId);
        if(rows == 0){
            logger.error("删除地图点位失败");
            return CommonResponse.createForError("删除地图点位失败");
        }
        logger.info("删除地图点位成功");
        return CommonResponse.createForSuccess("SUCCESS", null);
    }

    /**
     * 查询所有已保存地图（无分页功能）
     */
    @GetMapping("/nopage")
    public CommonResponse<List<Map>> getAllMaps(){
        List<Map> mapList = mapService.getAllMaps();

        if(mapList.isEmpty()){
            logger.error("无已保存地图");
            return CommonResponse.createForError("无已保存地图");
        }
        logger.info("查询地图成功");
        return CommonResponse.createForSuccess("SUCCESS", mapList);
    }

    /**
     * 查看可添加点位(注意这里的unit_id和map_nfc_msg要在unit表和nfc_management表中有对应数据)
     */
    @GetMapping("/extraPoints/{mapId}")
    public CommonResponse<List<MapDetailVO>> getExtraPoints(@PathVariable int mapId){
        List<MapDetailVO> mapDetailVOList = mapService.getExtraPoints(mapId);
        if(mapDetailVOList.isEmpty() || mapDetailVOList == null){
            logger.error("无可添加点位");
            return CommonResponse.createForError("无可添加点位");
        }
        logger.info("查看可添加点位成功");
        return CommonResponse.createForSuccess("SUCCESS", mapDetailVOList);
    }

}
